#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import autoUpdatePackConfig
import sgUtils
import sys

def getChannelArray():

	global updateConfigObj
	
	channelsdict = updateConfigObj.getChannelDict()
	channelsArray = []
	for channelname in channelsdict:
		if updateConfigObj.isChildChannel(channelname) == False:
			channelsArray.append(channelname)
	channelsArray.sort()
	
	return channelsArray

def getChildArray():

	global updateConfigObj
	
	channelsdict = updateConfigObj.getChannelDict()
	channelsArray = []
	for channelname in channelsdict:
		if updateConfigObj.isChildChannel(channelname) == True:
			channelsArray.append(channelname)
	channelsArray.sort()
	return channelsArray

def showChannels():
	channelsArray = getChannelArray()
	
	opChannelCnt = 0
	channels = "\n"
	for channelname in channelsArray:
		opChannelCnt = opChannelCnt + 1
		channels = channels+"<"+str(opChannelCnt)+"> "+channelname+"  "
		if opChannelCnt % 6 == 0:
			channels = channels + "\n\n"
	
	if opChannelCnt == 0:
		return
		
	channels = channels+"<all> 所有渠道\n\n"
	channels = channels+"选择要打包渠道(用空格分开)："
		
	# 等待选择渠道
	opChannelIdxs = input(channels)
	
	idxs = {}
	
	if opChannelIdxs == 'all':
		return channelsArray
	else:
		idxs = opChannelIdxs.split()
		
	idx = 0
	channelNames = []
	for opChannelIdx in idxs:
		if (int(opChannelIdx) <= opChannelCnt):
			channelNames.append(channelsArray[int(opChannelIdx)-1])
			idx = idx + 1
	return channelNames

def chooseChannelsWithName(channelname):
	channelsArray = getChannelArray()

	global updateConfigObj
	channelsdict = updateConfigObj.getChannelDict()

	if channelname == 'all':
		return channelsArray
	else:
		if channelname not in channelsdict:
			raise Exception("channelname",channelname,"is not in config!")

		channelNames = []
		channelNames.append(channelname)
		return channelNames

if __name__=="__main__":
	global updateConfigObj

	if( len(sys.argv) == 1 ):
		updateConfigObj = autoUpdatePackConfig.UpPackConfig("./userconfig/gameinfo.conf","./userconfig/channelinfolist.conf")

		channelNames = showChannels()
		if channelNames:
			for channelname in channelNames:
				print("channelname is",channelname)
				updateConfigObj.updateConfigInfoWithChannel(channelname)
			sgUtils.openPath("output")
	else:
		updateConfigObj = autoUpdatePackConfig.UpPackConfig("./userconfig/gameinfo.conf","./userconfig/channelinfolist.conf")

		channelname = sys.argv[1]
		channelNames = chooseChannelsWithName(channelname)
		if channelNames:
			for channelname in channelNames:
				print("channelname is",channelname)
				updateConfigObj.updateConfigInfoWithChannel(channelname)
			sgUtils.openPath("output")
